package com.example.week1.utils;

import android.os.Handler;
import android.widget.Toast;

import com.bumptech.glide.RequestBuilder;
import com.example.mylibrary.okhttp.MyCallBack;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class OkHttpUtils{
    private android.os.Handler handler=new Handler();
    OkHttpClient client;
    //单例
    private OkHttpUtils(){
        client = new OkHttpClient.Builder()
                .build();
    }
    private static OkHttpUtils okHttpUtils=new OkHttpUtils();
    public static OkHttpUtils getInstance(){
        if(okHttpUtils==null){
            okHttpUtils=new OkHttpUtils();
        }
        return okHttpUtils;
    }

    public void post(String url, HashMap<String, String> hashMap, MyCallBack myCallBack) {
        FormBody.Builder builder = new FormBody.Builder();
        Set<Map.Entry<String, String>> entries = hashMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            builder.add(entry.getKey(),entry.getValue());
        }
        FormBody build = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(build)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String message = e.getMessage();
              myCallBack.OnNo(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                myCallBack.OnOk(string);
            }
        });

    }


}
